package com.cskaoyan.controller;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.lihaoming.UserInfoBean;
import com.cskaoyan.bean.lihaoming.WeiXinUserData;
import com.cskaoyan.config.realm.MarketToken;
import com.cskaoyan.mapper.UserMapper;
import com.cskaoyan.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @author lihaoming
 * @Description
 * @Create 2022-06-29 14:28
 * @Version*/



@RestController
@RequestMapping("wx/auth")
public class WeixinAuthController {
    @Autowired
    UserMapper userMapper;
    @RequestMapping("login")
    public BaseRespVo WXLogin(@RequestBody Map map){
        String username = (String)map.get("username");
        String password = (String)map.get("password");

            //在这里要执行登录，Subject.login
            // → Subject只能作为局部变量，不能作为全局变量
            Subject subject = SecurityUtils.getSubject();
            // 执行登录（认证）
            //UsernamePasswordToken authenticationToken = new UsernamePasswordToken(username,password);
            MarketToken authenticationToken = new MarketToken(username, password, "wx");
            try {
                // realm.doGetAuthenticationInfo
                subject.login(authenticationToken);
            } catch (AuthenticationException e) {
                return BaseRespVo.error3();
            }

            // 判断是否认证成功
            boolean authenticated = subject.isAuthenticated();
            // 可以获得session信息，也可以获得其sessionId
            Session session = subject.getSession();



            // 获得Principal信息 → realm的doGetAuthorizationInfo方法构造的认证信息里的第一个参数

            MarketUser primaryPrincipal = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();


        WeiXinUserData weiXinUserData = new WeiXinUserData();
        UserInfoBean userInfo = new UserInfoBean();
            userInfo.setAvatarUrl(primaryPrincipal.getAvatar());
            userInfo.setNickName(primaryPrincipal.getUsername());
           weiXinUserData.setUserInfo(userInfo);
        weiXinUserData.setToken((String) session.getId());
           return BaseRespVo.ok(weiXinUserData);
    }
    @RequestMapping("logout")
    public BaseRespVo logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return BaseRespVo.ok();
    }
}
